﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;

namespace TTBox
{
    public enum TaxiStatus { Free, Forward, Reach, Pickup, Station, Rest, Suspend };

    public enum ButtonAction { C2Free, C2Forward, C2Reach, C2Pickup, C2Station, QueryStation, C2Rest, C2Suspend, Nothing, AddressError, MissPassenger, CancelJob, ShowAddress, Navi };
    public partial class MainScreenPanel : UserControl
    {


        internal enum Hwnd : int
        {
            HWND_TOP = 0,
            HWND_BOTTOM = 1,
            HWND_TOPMOST = -1,
            HWND_NOTOPMOST = -2
        }

        [DllImport("coredll.dll", SetLastError = true)]
        public static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndAfter, int xPos, int yPos, int cX, int cY, int wFlage);



        public MainScreenPanel()
        {
            InitializeComponent();
            this.timer_MainScreen.Enabled = true;

            
        }

        DateTime m_dtBox = System.DateTime.Now;

        public void updateDateTime(DateTime arg_dt)
        {
            m_dtBox = arg_dt;
            this.label_Date.Text = m_dtBox.ToString("yy/MM/dd");
           // this.label_Time.Text = m_dtBox.ToString("HH:mm:ss");
        }
        public void updateDateTime(int arg_nMS)
        {
            m_dtBox.AddMilliseconds(arg_nMS);
            this.label_Date.Text = m_dtBox.ToString("yy/MM/dd");
           // this.label_Time.Text = m_dtBox.ToString("HH:mm:ss");
        }


        string m_strRunOrderID = "0";
        string m_strRunJobData = "";

        DateTime m_dtMissPnr = System.DateTime.Now;
        DateTime m_dtCancelJob = System.DateTime.Now;
        DateTime m_dtAddrErr = System.DateTime.Now;

        public string RunOrderText
        {
            get
            {
                if (m_strRunJobData.Length > 19)
                {
                    return m_strRunJobData.Substring(19);
                }
                return "";
            }

        }

        public string RunOrderID { get { return m_strRunOrderID; } }

        public void sendCurrStatus()
        {
            string strResult = CmdTalker.getInstance().SendServerAndWaitResponse(m_strCurrStatus + "00" + m_strRunOrderID, 10, "MOK", false);

        }
        public void sendBackCancelSuccess()
        {
            string strResult = CmdTalker.getInstance().SendServerAndWaitResponse(m_strCurrStatus + "92" + m_strRunOrderID, 10, "MOK", false);

        }
        public void sendBackCancelSuccess(string arg_strJobID)
        {
            string strResult = CmdTalker.getInstance().SendServerAndWaitResponse(m_strCurrStatus + "92" + arg_strJobID, 10, "MOK", false);

        }


        public void setRunJobInfo(string arg_strOrderID, string arg_strJobData, int arg_nButtonMins)
        {
            m_strRunOrderID = arg_strOrderID;
            m_strRunJobData = arg_strJobData;

            if (arg_nButtonMins != -1)
            {
                m_dtMissPnr = System.DateTime.Now.AddMinutes(arg_nButtonMins + StoreData.getInstance().MissPnrExtendMins);
                m_dtCancelJob = System.DateTime.Now.AddMinutes(arg_nButtonMins + StoreData.getInstance().MissPnrExtendMins + StoreData.getInstance().CancelExtendMins * 10);
            }
            else
            {
                DateTime dt = getReserveJobDT(arg_strJobData);
                m_dtMissPnr = dt.AddMinutes(StoreData.getInstance().MissPnrExtendMins);
                m_dtCancelJob = dt.AddMinutes(StoreData.getInstance().MissPnrExtendMins + StoreData.getInstance().CancelExtendMins * 10);
            }
            

        }

        string m_strCurrStatus = "6";
        public string CurrRunOrderID { get { return m_strRunOrderID; } }
        public string CurrStatus { get { return m_strCurrStatus; } }

        public bool setStatus(TaxiStatus arg_status)
        {

            LogManager.getInstance().Log(" setStatus " + arg_status.ToString());

            string strResult = null;
            string strCmd = "00";

            switch (arg_status)
            {
                case TaxiStatus.Free:
                    strCmd = "60";
                    //SoundManager.getInstance().playFree();

                    break;
                case TaxiStatus.Forward:
                    strCmd = "62";

                    break;
                case TaxiStatus.Reach:
                    strCmd = "63";

                    break;
                case TaxiStatus.Pickup:
                    strCmd = "64";
                    //SoundManager.getInstance().playPickup();
                    break;

                case TaxiStatus.Rest:
                    strCmd = "65";

                    break;
                case TaxiStatus.Station:
                    strCmd = "61";


                    break;
            }

            strResult = CmdTalker.getInstance().SendServerAndWaitResponse(m_strCurrStatus + strCmd + m_strRunOrderID, 10, "MOK", true);

            if (strResult != "MOK" && Form_Main.Main.m_bLogined)
            {
                return false;
            }

            setButton(button_F1, ButtonAction.Nothing, "");
            setButton(button_F2, ButtonAction.Nothing, "");
            setButton(button_F3, ButtonAction.Nothing, "");
            setButton(button_F4, ButtonAction.Nothing, "");
            if (StoreData.getInstance().IsNaviEnable)
            {
                setButton(button_F5, ButtonAction.Navi, null);
            }
            else
            {
                button_F5.Visible = false;
            }

            
                
            switch (arg_status)
            {
                case TaxiStatus.Free:

                        

                    this.label_Title.Text = "空車";

                    m_strRunOrderID = "0";
                    setButton(this.button_F1, ButtonAction.C2Pickup, "路攔");
                    setButton(this.button_F2, ButtonAction.C2Station, null);
                    setButton(this.button_F3, ButtonAction.C2Rest, null);
                    setButton(this.button_F4, ButtonAction.QueryStation, null);

                    m_strCurrStatus = "0";

                    break;
                case TaxiStatus.Forward:

                    this.label_Title.Text = "前往";

                    setButton(this.button_F1, ButtonAction.ShowAddress, null);
                    setButton(this.button_F2, ButtonAction.C2Reach, null);
                    setButton(this.button_F4, ButtonAction.AddressError, null);

                    m_strCurrStatus = "2";
                    

                    break;
                case TaxiStatus.Reach:

                    this.label_Title.Text = "到達";

                    setButton(this.button_F1, ButtonAction.C2Pickup, "上車");
                    //TODO: 等候時間, 顯示出客取消及未見客
                    setButton(this.button_F2, ButtonAction.CancelJob, null);
                    this.button_F2.Visible = false;
                    setButton(this.button_F4, ButtonAction.MissPassenger, null);
                    this.button_F4.Visible = false;

                    checkButtonDT();

                    m_strCurrStatus = "3";
                    
                    break;

                case TaxiStatus.Pickup:

                    this.label_Title.Text = "載客";

                    setButton(this.button_F1, ButtonAction.C2Free, null);
                    setButton(this.button_F4, ButtonAction.QueryStation, null);

                    m_strCurrStatus = "4";


                    break;
                
                case TaxiStatus.Rest:

                    this.label_Title.Text = "休息";

                    setButton(this.button_F1, ButtonAction.C2Free, "工作");
                    setButton(this.button_F2, ButtonAction.C2Station, null);
                    setButton(this.button_F3, ButtonAction.C2Pickup, "路攔");
                    setButton(this.button_F4, ButtonAction.QueryStation, null);

                    m_strCurrStatus = "5";


                    break;

                case TaxiStatus.Station:

                    this.label_Title.Text = "排班";

                    setButton(this.button_F1, ButtonAction.C2Free, "消班");
                    setButton(this.button_F2, ButtonAction.C2Pickup, "路攔");
                    setButton(this.button_F4, ButtonAction.QueryStation, null);

                    m_strCurrStatus = "1";

                    break;
               
            }

            return true;

            
        }
        private void setButton(Button arg_bt, ButtonAction arg_ba, string arg_strAltTitle)
        {
            if(arg_ba != ButtonAction.Nothing)
                arg_bt.Visible = true;
            switch (arg_ba)
            {
                case ButtonAction.AddressError:
                    arg_bt.Text = "錯誤";
                    break;
                case ButtonAction.C2Forward:
                    arg_bt.Text = "前往";
                    break;
                case ButtonAction.C2Free:
                    arg_bt.Text = "下車";
                    break;
                case ButtonAction.C2Pickup:
                    arg_bt.Text = "上車";
                    break;
                case ButtonAction.C2Reach:
                    arg_bt.Text = "到達";
                    break;
                case ButtonAction.C2Rest:
                    arg_bt.Text = "休息";
                    break;
                case ButtonAction.C2Station:
                    arg_bt.Text = "排班";
                    break;
                case ButtonAction.C2Suspend:
                    arg_bt.Text = "停派";
                    break;
                case ButtonAction.CancelJob:
                    arg_bt.Text = "放棄";
                    break;
                case ButtonAction.MissPassenger:
                    arg_bt.Text = "催客";
                    break;
                case ButtonAction.Nothing:
                    arg_bt.Visible = false;
                    arg_bt.Text = "無";
                    break;
                case ButtonAction.QueryStation:
                    arg_bt.Text = "查班";
                    break;
                case ButtonAction.ShowAddress:
                    arg_bt.Text = "地址";
                    break;
                case ButtonAction.Navi:
                    arg_bt.Text = "導航";
                    break;

                default:
                    //Todo:error
                    MessageBox.Show("Error No :" + arg_ba.ToString());
                    break;
            }
            arg_bt.Tag = arg_ba;
            if (arg_strAltTitle != null)
            {
                arg_bt.Text = arg_strAltTitle;
            }
        }

        private void button_Dispatch_Click(object sender, EventArgs e)
        {
            Form_Main.Main.resetBackLightTimeout(); 
            Form_Main.Main.ChangeToDispatchMsg();
        }

        private void MainScreenPanel_KeyPress(object sender, KeyPressEventArgs e)
        {
            switch (e.KeyChar)
            {
                case 'A':

                    break;

                default :
                    button_F5.Text = ""+ e.KeyChar;
                    break;
            }
        }

        System.Diagnostics.Process m_pNavi = null;
        System.Diagnostics.Process m_pNaviBack = null;

        public class MemoryStatus
        {
            [DllImport("coredll.dll")]
            public static extern void GlobalMemoryStatus(ref MEMORYSTATUS lpBuffer);

            public struct MEMORYSTATUS
            {
                public int dwLength;
                public int dwMemoryLoad;
                public int dwTotalPhys;
                public int dwAvailPhys;
                public int dwTotalPageFile;
                public int dwAvailPageFile;
                public int dwTotalVirtual;
                public int dwAvailVirtual;
            };

            const string CRLF = "\r\n";
            public static string GetStatus()
            {
                MEMORYSTATUS ms = new MEMORYSTATUS();
                ms.dwLength = Marshal.SizeOf(ms);
                GlobalMemoryStatus(ref ms);
                StringBuilder sbMessage = new StringBuilder();
                sbMessage.Append("Me");
                sbMessage.Append(ms.dwMemoryLoad.ToString() + "%");
                sbMessage.Append(CRLF);
                sbMessage.Append("TR");
                sbMessage.Append((ms.dwTotalPhys/1000).ToString("#,##0"));
                sbMessage.Append(CRLF);
                sbMessage.Append("AR");
                sbMessage.Append((ms.dwAvailPhys / 1000).ToString("#,##0"));
                sbMessage.Append(CRLF);
                sbMessage.Append("TP");
                sbMessage.Append((ms.dwTotalPageFile / 1000).ToString("#,##0"));
                sbMessage.Append(CRLF);
                sbMessage.Append("AP");
                sbMessage.Append((ms.dwAvailPageFile / 1000).ToString("#,##0"));
                sbMessage.Append(CRLF);
                sbMessage.Append("TV");
                sbMessage.Append((ms.dwTotalVirtual / 1000).ToString("#,##0"));
                sbMessage.Append(CRLF);
                sbMessage.Append("AV");
                sbMessage.Append((ms.dwAvailVirtual / 1000).ToString("#,##0"));
                return sbMessage.ToString();
            }
        }

        DateTime dtLogMemory = System.DateTime.Now.AddSeconds(10);
        public DateTime dtReNavi = System.DateTime.Now.AddHours(1000);
        bool m_bReOpenNavi = false;

        private void LogMemory()
        {
            if (dtLogMemory < System.DateTime.Now)
            {
                dtLogMemory = System.DateTime.Now.AddSeconds(10);
                LogManager.getInstance().Log(MemoryStatus.GetStatus());
            }
            if (m_bReOpenNavi && dtReNavi < System.DateTime.Now)
            {
                dtReNavi = System.DateTime.Now.AddHours(1);
                RunNavi();
                LogManager.getInstance().Log("ReNavi By Timer", new Exception("ReNavi By Timer"));

            }
        }

        private void button_F1_Click(object sender, EventArgs e)
        {

            Button bSend = (Button)sender;

            Form_Main.Main.resetBackLightTimeout();

            LogManager.getInstance().Log(" Click " + bSend.Text);

            string strResult;
            if (bSend.Tag  != null)
            {
                LogManager.getInstance().Log(" Click Tag:" + bSend.Tag.ToString());

                ButtonAction ba = (ButtonAction)bSend.Tag;
                switch (ba)
                {
                    case ButtonAction.AddressError:

                        strResult = CmdTalker.getInstance().SendServerAndWaitResponse(m_strCurrStatus + "70" + m_strRunOrderID, 10, "MOK", true);

                        if (strResult != "MOK")
                        {
                            
                        }
                        m_dtAddrErr = System.DateTime.Now.AddSeconds(StoreData.getInstance().JobEventBtnNextSecs);
                        bSend.Enabled = false;

                        break;
                    case ButtonAction.C2Forward:
                        this.setStatus(TaxiStatus.Forward);
                        break;
                    case ButtonAction.C2Free:
                        if (bSend.Text == "下車")
                        {
                            SoundManager.getInstance().playFree();
                        }
                        this.setStatus(TaxiStatus.Free);

                        break;
                    case ButtonAction.C2Pickup:
                        if (bSend.Text == "路攔" || bSend.Text == "上車")
                        {
                            SoundManager.getInstance().playPickup();
                        }
                        this.setStatus(TaxiStatus.Pickup);

                        break;
                    case ButtonAction.C2Reach:
                        this.setStatus(TaxiStatus.Reach);

                        //重新計算 未見客及客取消按鈕出現的時間
                        if (m_dtMissPnr < System.DateTime.Now.AddMinutes(StoreData.getInstance().MissPnrExtendMins))
                        {
                            m_dtMissPnr = System.DateTime.Now.AddMinutes(StoreData.getInstance().MissPnrExtendMins);
                        }
                        if (m_dtCancelJob < System.DateTime.Now.AddMinutes(StoreData.getInstance().MissPnrExtendMins + StoreData.getInstance().CancelExtendMins * 10))
                        {
                            m_dtCancelJob = System.DateTime.Now.AddMinutes(StoreData.getInstance().MissPnrExtendMins + StoreData.getInstance().CancelExtendMins * 10);
                        }

                        this.button_F2.Visible = false;
                        this.button_F4.Visible = false;

                        break;
                    case ButtonAction.C2Rest:
                        this.setStatus(TaxiStatus.Rest);
                        break;
                    case ButtonAction.C2Station:
                        this.setStatus(TaxiStatus.Station);
                        break;
                    case ButtonAction.C2Suspend:
                        this.setStatus(TaxiStatus.Suspend);
                        break;
                    case ButtonAction.CancelJob:
                        strResult = CmdTalker.getInstance().SendServerAndWaitResponse(m_strCurrStatus + "72" + m_strRunOrderID, 10, "MOK", true);
                        if (strResult != "MOK")
                        {
                        }
                        setStatus(TaxiStatus.Free);

                        break;
                    case ButtonAction.MissPassenger:
                        
                        strResult = CmdTalker.getInstance().SendServerAndWaitResponse(m_strCurrStatus + "71" + m_strRunOrderID, 10, "MOK", true);

                        if (strResult != "MOK")
                        {
                        }
                        m_dtMissPnr = System.DateTime.Now.AddMinutes(StoreData.getInstance().MissPnrExtendMins);
                        m_dtCancelJob = System.DateTime.Now.AddMinutes(StoreData.getInstance().CancelExtendMins);
                        bSend.Visible = false;

                        break;
                    case ButtonAction.Nothing:

                        break;

                    case ButtonAction.QueryStation:
                        strResult = CmdTalker.getInstance().SendServerAndWaitResponse(m_strCurrStatus + "81", 10, "MOK", true);

                        if (strResult != "MOK")
                        {
                        }

                        break;
                    case ButtonAction.ShowAddress:

                        Form_Main.Main.ChangeToJobRead(this.m_strRunJobData.Substring(4), -1);

                        break;
                    case ButtonAction.Navi:
                        RunNavi();
                        break;


                }
            }
        }

        private void RunNavi()
        {
            //return;
            //Form_Main.Main.ChangeToNavi();
            //TODO:如果是在前往狀態, 將目的地設定過去
            try
            {
                /*if (m_strCurrStatus == "2")
                {
                    string[] strary = m_strRunJobData.Split('\t');
                    if (strary.Length >= 2)
                    {
                        string[] straryLoc = strary[1].Split(',');
                        //TODO:設定目的地
                        Form_Main.Main.SetDestByLonLat(straryLoc[0], straryLoc[1]);
                    }
                }*/
                bool bHasExist = false;
                LogManager.getInstance().Log(Form_Main.Main.WindowState.ToString() + ":" + FormWindowState.Maximized.ToString());
                //if (this.button_ExitNavi.Visible == false)
                {
                    //this.button_ExitNavi.Visible = true;

                    if (m_pNavi != null)
                    {
                        /*if (m_pNavi.HasExited)
                        {
                            LogManager.getInstance().Log("Navi Die");
                            m_pNavi = null;
                        }
                        else if (m_strCurrStatus == "2")*/
                        {
                            try
                            {
                                m_pNavi.Close();
                                m_pNavi = null;
                                LogManager.getInstance().Log("Close Navi OK");
                                bHasExist = true;
                            }
                            catch (Exception ex)
                            {
                                LogManager.getInstance().Log("Close Navi 2 Error", ex);
                                m_pNavi = null;
                            }
                            /*
                            try
                            {
                                m_pNaviBack.Close();
                                m_pNaviBack = null;
                                LogManager.getInstance().Log("Close NaviBack OK");
                            }
                            catch (Exception ex)
                            {
                                LogManager.getInstance().Log("Close NaviBack 2 Error", ex);
                                m_pNaviBack = null;
                            }*/

                        }
                    }

                    if (m_pNavi == null)
                    {
                        dtReNavi = System.DateTime.Now.AddHours(1);
                        LogManager.getInstance().Log("Start Navi ..");
                        m_pNavi = new System.Diagnostics.Process();

                        string strParms = "";
                        if (m_strCurrStatus == "2")
                        {
                            string[] strary = m_strRunJobData.Split('\t');
                            if (strary.Length >= 2)
                            {
                                string[] straryLoc = strary[1].Split(',');
                                //TODO:設定目的地
                                strParms = " AppRunNaviTo " + straryLoc[0] + " " + straryLoc[1];
                            }
                        }


                        m_pNavi.StartInfo = new System.Diagnostics.ProcessStartInfo("\\FlashDisk\\PNDsoftware1\\Navi\\Navigator.exe", strParms);
                        m_pNavi.Start();
                        // if(!bHasExist)
                        //     System.Threading.Thread.Sleep(10000);
                        // else
                        //System.Threading.Thread.Sleep(3000);

                        LogManager.getInstance().Log("NaviOK:" + m_strCurrStatus + ";" + strParms);
                    }
                    else
                    {
                        /*
                        Form_Main.Main.SetTopMost(false);
                        Form_Main.Main.SendToBack();
                        Form_Main.Main.Refresh();
                        m_pNavi.Refresh();
                        */

                    }

                    if (m_pNaviBack != null)
                    {
                        try
                        {
                            if (m_pNaviBack.HasExited)
                            {
                                LogManager.getInstance().Log("Kill NaviBack.");

                                m_pNaviBack.Kill();


                                m_pNaviBack = null;

                            }
                        }
                        catch (Exception ex3)
                        {
                            LogManager.getInstance().Log("Close NaviBack  Error", ex3);
                        }


                    }
                    if (m_pNaviBack == null)
                    {
                        LogManager.getInstance().Log("Start m_pNaviBack ..");
                        string strParms = Form_Main.Main.Handle.ToString();

                        m_pNaviBack = new System.Diagnostics.Process();
                        m_pNaviBack.StartInfo = new System.Diagnostics.ProcessStartInfo("\\FlashDisk\\PNDsoftware\\TTNaviBack.exe", strParms);
                        m_pNaviBack.Start();
                        LogManager.getInstance().Log("m_pNaviBack OK:" + strParms);
                        m_bReOpenNavi = true;
                    }
                    else
                    {
                        LogManager.getInstance().Log("Send m_pNaviBack ..");
                        CmdTalker.getInstance().SendNaviButtonShow();
                        /*
                        Form_Main.Main.SetTopMost(false);
                        Form_Main.Main.SendToBack();
                        Form_Main.Main.Refresh();
                        m_pNavi.Refresh();
                        */

                    }

                    //Form_Main.Main.WindowState = FormWindowState.Normal;
                    //Form_Main.Main.Left = -(Form_Main.Main.Width - 90);
                    //Form_Main.Main.Top = -(Form_Main.Main.Height - 20);
                    //Form_Main.Main.Height = 52;
                    //Form_Main.Main.Width = 90;
                    //Form_Main.Main.SetTopMost(true);
                    //m_dtNextSetTopMost = System.DateTime.Now.AddSeconds(3);

                }


            }
            catch (Exception ex)
            {
                LogManager.getInstance().Log("Error:" + m_strCurrStatus + ":" + m_strRunJobData, ex);
            }
        }

        public void SetNaviWindow()
        {
            try
            {
                if (m_pNavi != null)
                {
                    SetWindowPos(m_pNavi.MainWindowHandle, new IntPtr(-2), 0, 0, 480, 272, 0);
                }
            }
            catch (Exception ex)
            {
                LogManager.getInstance().Log("SetNaviWin Err", ex);
            }
        
        }

        public void checkButtonDT()
        {
            if (CurrStatus == "3")
            {
                if (!button_F2.Visible && m_dtCancelJob < System.DateTime.Now)
                    button_F2.Visible = button_EM.Enabled;
                if (!button_F4.Visible && m_dtMissPnr < System.DateTime.Now)
                {
                    button_F4.Visible = button_EM.Enabled;
                }
                if (!button_F4.Enabled && m_dtMissPnr < System.DateTime.Now)
                {
                    button_F4.Enabled = button_EM.Enabled;
                }

            }
            if (CurrStatus == "2")
            {
                if (!button_F4.Enabled && m_dtAddrErr < System.DateTime.Now)
                {
                    button_F4.Enabled = button_EM.Enabled;
                }
            }

            
            if (this.button_ReserveJob.Tag != null)
            {
                DateTime dt = (DateTime)this.button_ReserveJob.Tag;

                if (dt.AddMinutes(StoreData.getInstance().ReserveJobAlarmMins * -1) < System.DateTime.Now)
                {
                    this.button_ReserveJob.BackColor = Color.FromArgb(StoreData.getInstance().WarningBackColor);
                }
                else
                {
                    this.button_ReserveJob.BackColor = Color.FromArgb(StoreData.getInstance().ButtonBackColor);
                }
            }


            if (!button_F1.Enabled && m_dtDisableButtonOneSec < System.DateTime.Now && !Form_Main.Main.IsSendAndWait) 
            {
                button_F1.Enabled = true;
                //if(button_F2.Text != "離開")
                    button_F2.Enabled = true;
                //if(button_F3.Text != "未見" )
                    button_F3.Enabled = true;
                //if(button_F4.Text != "錯誤")
                    button_F4.Enabled = true;

                    button_F5.Enabled = true;
                    button_EM.Enabled = true;

            }
            



        }

        DateTime m_dtNextSetTopMost = System.DateTime.Now.AddSeconds(5);

        private void timer_MainScreen_Tick(object sender, EventArgs e)
        {
            string str  = System.DateTime.Now.ToString("MM/dd HH:mm:");
            if (str != this.label_Date.Text)
            {
                this.label_Date.Text = str;
                this.label_Date.Refresh();
            }
            str = System.DateTime.Now.ToString("ss");
            if (str != this.label_Seconds.Text)
            {
                this.label_Seconds.Text = str;
                this.label_Seconds.Refresh();
            }
            
            //if (this.label_Date.Text[0] == '0')
            //    this.label_Date.Text = " " + this.label_Date.Text.Substring(1);
            //this.label_Time.Text = System.DateTime.Now.ToString("hh:mm:ss");
            //this.panel_DateTime.Refresh();

            checkButtonDT();

            //Application.DoEvents();

            //if (m_dtNextSetTopMost < System.DateTime.Now)
            //{
            //    m_dtNextSetTopMost = System.DateTime.Now.AddSeconds(5);
            //    LogManager.getInstance().Log("SetTM");
            //    Form_Main.Main.SetTopMost(true);
            //}


            LogMemory();

        }

        private void button_SituationReport_Click(object sender, EventArgs e)
        {
            Form_Main.Main.resetBackLightTimeout();
            Form_Main.Main.ChangeToSReport();
        }

        private void button_Msg_Click(object sender, EventArgs e)
        {
            Form_Main.Main.resetBackLightTimeout();
            Form_Main.Main.ChangeToMsg();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Form_Main.Main.resetBackLightTimeout();
            TimeSpan ts = System.DateTime.Now.Subtract(dtEmergency);

            if (ts.TotalMilliseconds > 1800)
            {
                sendEMStatus(true);
                dtEmergency = System.DateTime.Now;
                this.button_F1.Focus();
            }
            else
            {
                Form_Main.Main.resetBackLightTimeout();
                Form_Main.Main.ChangeToSysConfig();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Form_Main.Main.ChangeToInputPanel();
        }

        public void CancelJobCheck(string arg_strOrderID)
        {
            if (arg_strOrderID == m_strRunOrderID)
            {

                string strResult = CmdTalker.getInstance().SendServerAndWaitResponse(m_strCurrStatus + "92" + m_strRunOrderID, 10, "MOK", true);

                if (strResult != "MOK")
                {
                }
            }

        }

        public void UnEmergency()
        {
            this.button_EM.Visible = false;
        }

        private void button_S_Click(object sender, EventArgs e)
        {

            Form_Main.Main.resetBackLightTimeout();
            TimeSpan ts = System.DateTime.Now.Subtract(dtEmergency);

            if (ts.TotalMilliseconds > 1800)
            {
                sendEMStatus(true);
            }
            dtEmergency = System.DateTime.Now;
            this.button_F1.Focus();


        }

        public void sendEMStatus(bool arg_bNeedSend)
        {
            this.button_EM.Visible = true;
            if (arg_bNeedSend)
            {
                string strResult = CmdTalker.getInstance().SendServerAndWaitResponse(m_strCurrStatus + "99", 10, "MOK", false);

                if (strResult != "MOK")
                {
                }
            }
        }

        DateTime dtEmergency = System.DateTime.Now;

        public void checkReserveJobButton()
        {
            try
            {
                SortedList slJob = StoreData.getInstance().getReserveJobBySorted();
                if (slJob.Count == 0)
                {
                    this.button_ReserveJob.BackColor = Color.FromArgb(StoreData.getInstance().ButtonBackColor);

                    this.button_ReserveJob.Text = "預約派遣";
                    this.button_ReserveJob.Tag = null;
                }
                else
                {
                    string strDT = (string)slJob.GetByIndex(0);
                    DateTime dt = getReserveJobDT(strDT);
                    this.button_ReserveJob.Text = "預約 " + dt.ToString("MM/dd HH:mm");
                    this.button_ReserveJob.Tag = dt;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }

        DateTime m_dtDisableButtonOneSec = System.DateTime.Now;
        public void disableButtonOneSec()
        {
            m_dtDisableButtonOneSec = System.DateTime.Now.AddMilliseconds(500);
            this.button_F1.Enabled = false;
            this.button_F2.Enabled = false;
            this.button_F3.Enabled = false;
            this.button_F4.Enabled = false;
            this.button_EM.Enabled = false;
            this.button_F5.Enabled = false;
        }

        private DateTime getReserveJobDT(string arg_strJobData)
        {
            try
            {

                
                int nLoc = arg_strJobData.IndexOf('/');
                string strDT = arg_strJobData.Substring(nLoc - 2, 11);
                int nMM = System.Convert.ToInt32(strDT.Substring(0, 2));
                int ndd = System.Convert.ToInt32(strDT.Substring(3, 2));
                int nHH = System.Convert.ToInt32(strDT.Substring(6, 2));
                int nmm = System.Convert.ToInt32(strDT.Substring(9, 2));

                int nyy = System.DateTime.Now.Year;

                if (nMM < System.DateTime.Now.Month)
                    nyy += 1;

                DateTime dt = new DateTime(nyy, nMM, ndd, nHH, nmm, 0);
                return dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }

            return System.DateTime.Now;



        }

        private void button_ReserveJob_Click(object sender, EventArgs e)
        {
            Form_Main.Main.resetBackLightTimeout();
            Form_Main.Main.ChangeToReserveJobMsg();
        }

        private void button1_GotFocus(object sender, EventArgs e)
        {
            dtEmergency = System.DateTime.Now;

        }

        private void button_ExitNavi_Click(object sender, EventArgs e)
        {
            try
            {
                this.button_ExitNavi.Visible = false;
                Form_Main.Main.WindowState = FormWindowState.Maximized;
                this.Refresh();
                Form_Main.Main.SetTopMost(true);
                LogManager.getInstance().Log("ReturnToTTBox");
            }
            catch (Exception ex)
            {
                LogManager.getInstance().Log("RETUEN ERR", ex);
            }
        }

    }
}
